<template>
  <view class="o-page-content cofs-page">
    <!-- <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar> -->
    <view class="rma_express">
      <view class="expForm">
        <view>请填写寄回快递信息：</view>
        <view class="listMob">
          <label>快递公司</label>
          <picker :value="expressIdx" :range-key="'expressName'" :range="expressList" @change="bindPickerChange" mode="selector">
            <view class="picker">{{ expressName ? expressName : '请选择' }}</view>
            <text class="a-icon-arrow-down-small"></text>
          </picker>
        </view>
        <view class="m-input">
          <label>快递单号</label>
          <input class="a-input" name="expressNumber" @blur="expressNumberInput" placeholder="请填写物流单号" />
        </view>
      </view>
      <!-- 退货商品 -->
      <view class="refundItems">
        <view class="pageTitle">退货商品信息：</view>
        <block v-for="(item, index) in listItems" :key="index">
          <view class="good_list">
            <view class="image_box"><image :src="item.skuImageUrl" :style="{ height: imageHeight + 'rpx' }"></image></view>
            <view class="textInfo">
              <strong>{{ item.itemName }}</strong>
              <p>货号：{{ item.skuCode }}</p>
              <p>{{ item.skuProperties[0].pripertyName ? item.skuProperties[0].pripertyName : item.skuProperties[0].propertyName }}：{{ item['skuProperties'][0].valueName }}</p>
              <p :style="{ opacity: item.skuProperties[1] ? '1' : '0' }">
                {{ item.skuProperties[1].pripertyName ? item.skuProperties[1].pripertyName : item.skuProperties[1].propertyName }}：{{ item['skuProperties'][1].valueName }}
              </p>
            </view>
            <view class="goods">
              <view class="product_name">{{ item.orderType }}</view>
              <view class="product_rule">规格:{{ item.skuCode }}</view>
              <view class="product_info">
                <view class="price">{{ '¥ ' + item.price }}</view>
                <view class="goods_num">{{ item.qty ? item.qty : item.num }}件</view>
              </view>
            </view>
          </view>
        </block>
      </view>
      <view class="refundItems" v-if="otherRefundItem">
        <view class="pageTitle">您还可以选择以下寄出</view>
        <view class="pageTitle">退货商品信息:</view>
        <block v-for="(canRelogItem, index) in refundItemsJson" :key="index">
          <view class="good_list" v-for="(relogItem, itemsIndex) in canRelogItem.items" :key="itemsIndex">
            <view class="label-1__icon" @click="selectTap" :data-index="itemsIndex > 1 ? itemsIndex : index" :data-refund="canRelogItem.refundId">
              <icon v-if="canRelogItem.checked == true" size="13" class="icon_check" type="success_no_circle" color="#444444" />
            </view>
            <view class="image_box"><image :style="{ height: imageHeight + 'rpx' }" :src="relogItem.skuImageUrl"></image></view>
            <view class="textInfo">
              <strong>{{ relogItem.itemName }}</strong>
              <p>货号：{{ relogItem.skuCode }}</p>
              <p>
                {{ relogItem.skuProperties[0].pripertyName ? relogItem.skuProperties[0].pripertyName : relogItem.skuProperties[0].propertyName }}：{{
                  relogItem['skuProperties'][0].valueName
                }}
              </p>
              <p :style="{ opacity: relogItem.skuProperties[1] ? '1' : '0' }">
                {{ relogItem.skuProperties[1].pripertyName ? relogItem.skuProperties[1].pripertyName : relogItem.skuProperties[1].propertyName }}：{{
                  relogItem['skuProperties'][1].valueName
                }}
              </p>
            </view>
            <view class="goods">
              <view class="product_name">{{ relogItem.orderType }}</view>
              <view class="product_rule">规格:{{ relogItem.skuCode }}</view>
              <view class="product_info">
                <view class="price">{{ '¥ ' + relogItem.price }}</view>
                <view class="goods_num">{{ relogItem.qty ? relogItem.qty : relogItem.num }}件</view>
              </view>
            </view>
          </view>
        </block>
      </view>
      <view class="ramAddress">
        <strong class="is-black">退货地址：</strong>
        <view class="address">
          <p @longpress="copy(list.address)">
            {{ list.address }}
            <text @click="copy(list.address)" class="copy-btn">复制</text>
          </p>
          <p>{{ '收货人：' + list.receiverName }}</p>
          <p>{{ '电话：' + list.receiverMobile }}</p>
        </view>
      </view>
      <view class="bottom-section text-center rmaRet">
        <button class="a-button is-primary" :class="expressName && expressNumber ? '' : 'btn_invalid'" @click="toRmaReturn">提交</button>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script>
import api from '@/api/api';
// import NavBar from '../../components/common/navbar';
import { SYSTEM_INFO, CUSTOMER_INFO } from '@/utils/constant';

export default {
  config: {
    navigationBarTitleText: '详情信息'
  },
  // components: {
  //   navBar: NavBar
  // },
  data() {
    return {
      // isShowCustomNavBar: true,
      // // 组件所需的参数
      // navbarData: {
      //   showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      //   title: '' //导航栏 中间的标题
      // },
      otherRefundItem: false,
      orderList: [],
      list: [],
      listItems: [],
      refundIdArr: [],
      expressNumber: '',
      refundId: '',
      orderNo: '',
      orderStatus: '',
      expressList: [],
      expressIdx: 0,
      expressName: '',
      expressCode: '',
      option: '',
      express_number: '',
      addressDetail: '',
      refundItem: [],
      refundAddress: '江苏省昆山市新生路718号 江苏省富莱德仓储有限公司物流园一期B幢仓库B-1单元',
      consignee: '收货人：' + this.$store.state.storeName + '退货组',
      Email: '电子邮箱：customerservice.cn@cosstores.com',
      telephone: '电话：400-0151-365',
      refundOrderList: [],
      refundItemsStatus: [],
      canRefundItems: [],
      refundItemsJson: [],
      imageHeight: 180,
      nowPages:'',
    };
  },
  onLoad(options) {
    let that = this;
    this.imageHeight = 120 / uni.getStorageSync('imageScaling');
    this.refundId = options.refundId;
    this.orderNo = options.orderNo;
    this.getRefundInfo();
    this.getOrderInfo();
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    this.nowPages = currPage.route;
  },
  onShow() {
       getApp().cl_tracker.track('mini_program_view', {
             path:  this.nowPages,
             pageName: '填写退货物流信息',
           })
     },
  methods: {
		/**
		 * 展示弱提示
		 * @param {Object} msg 文案
		 */
		handleShowTextToast(msg){
			try{
				this.$refs.toastPopup.showToast(msg);
			}catch(e){}
		},
		/**
		 * 若提示按钮点击回调
		 * @param {Object} data.type 类型：confirm确定，cancel取消
		 * @param {Object} data.callBackData 呼气弹窗时传入的数据
		 */
		onToastPopupClick(data){},
    selectTap(e) {
      let that = this;
      let index = e.currentTarget.dataset.index;
      let otherRefundId = e.currentTarget.dataset.refund;
      this.canRefundItems[index].checked = !this.canRefundItems[index].checked;
      this.refundIdArr = [];
      for (let i in this.canRefundItems) {
        if (this.canRefundItems[i].checked == true) {
          if (this.refundIdArr.indexOf(this.canRefundItems[i].refundId) == -1) {
            this.refundIdArr.push(this.canRefundItems[i].refundId);
          }
        }
      }
    },

    // 根据订单号查询详情 其它待退货商品
    getOrderInfo: async function() {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      const json = await api.getOrderInfo(
        {
          header: {
            jwt: customerInfo.jwt
          }
        },
        this.orderNo
      );
      if (json.code === 1000) {
        // let orderItem = json.data;
        let orderItem = json.data.items;
        //解析每个数组下面的items.skuProperties属性
        orderItem.forEach(function(item, index, array) {
          orderItem[index].skuProperties = JSON.parse(array[index].skuProperties);
          orderItem[index].checked = false;
          if (orderItem[index].refundStatus == 'WAIT_BUYER_RETURN_GOODS') {
            that.orderList.push(orderItem[index]);
          }
        });

        that.getRefundOrderStatus();
      } else {
        that.handleShowTextToast(json.data.msg);
      }
    },

    getRefundOrderStatus: async function() {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)

      for (let k in that.orderList) {
        const refundOrderJson = await api.getRefundListByOrderItemId(
          {
            header: {
              jwt: customerInfo.jwt
            }
          },
          that.orderList[k].orderItemId
        );

        that.orderList[k].refundOrderItems = [];
        if (refundOrderJson.code === 1000) {
          that.refundOrderList = refundOrderJson.data;

          that.refundOrderList.forEach(function(item, index, array) {
            that.refundOrderList[index].skuProperties = JSON.parse(array[index].skuProperties);
            that.refundOrderList[index].checked = false;

            if (that.refundOrderList[index].refundId != that.refundId && array[index].status == 'WAIT_BUYER_RETURN_GOODS') {
              that.canRefundItems.push(that.refundOrderList[index]);
            }

            for (let z in array[index].items) {
              array[index].items[z].skuProperties = JSON.parse(array[index].items[z].skuProperties);
            }
          });

          if (that.canRefundItems.length > 0) {
            that.refundItemsJson = this.unique(that.canRefundItems);

            that.orderList[k].refundOrderItems = that.canRefundItems;
            that.otherRefundItem = true;
          } else {
            that.otherRefundItem = false;
          }
        }
      }
    },

    // 去重
    unique: function(arr) {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].refundId == arr[j].refundId) {
            //第一个等同于第二个，splice方法删除第二个
            arr.splice(j, 1);
            j--;
          }
        }
      }
      return arr;
    },

    // getRefundInfo 退款单详情
    getRefundInfo: async function() {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      const json = await api.getRefundInfo(
        {
          header: {
            jwt: customerInfo.jwt
          }
        },
        this.refundId
      );
      if (json.code === 1000) {
        this.refundAddress = json.data.address;
        this.consignee = json.data.receiverName;
        this.telephone = json.data.receiverMobile;
        this.orderNo = json.data.orderId;
        this.orderStatus = json.data.status;
        that.list = json.data;
        that.listItems = json.data.items;
        //解析每个数组下面的items.skuProperties属性
        that.listItems.forEach(function(item, index, array) {
          that.listItems[index].skuProperties = JSON.parse(array[index].skuProperties);
        });
        this.getExpressList();
      } else {
        this.handleShowTextToast(json.msg);
      }
    },
    // 获取物流公司列表
    getExpressList: async function() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      const json = await api.expressList({
        header: {
          jwt: customerInfo.jwt
        }
      });
      if (json.code === 1000) {
        this.expressList = json.data;
      }
    },
    copy(content) {
      var that = this;
      let copy = this.refundAddress + ' ' + this.consignee + ' ' + this.telephone
      uni.setClipboardData({
        data: copy,
        success: function(res) {
          uni.showToast({
            title: '复制成功'
          });
        }
      });
    },
    bindPickerChange: function(e) {
      this.expressIdx = e.detail.value;
      this.expressName = this.expressList[this.expressIdx].expressName;
      this.expressCode = this.expressList[this.expressIdx].expressCode;
    },
    expressNumberInput(e) {
      this.expressNumber = e.detail.value;
    },

    writeRefundInfo: async function() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      const json = await api.buyerReturn({
        method: 'POST',
        header: {
          jwt: customerInfo.jwt
        },
        query: {
          expressCode: this.expressCode,
          refundId: this.refundId,
          trackingNumber: this.expressNumber
        }
      });
      if (json.code === 1000) {
        uni.redirectTo({
          url: '/pages/return/applySuccess?orderNo=' + this.orderNo + '&refundId=' + this.refundId
        });
      } else {
        if (json.msg == 'expressCode不正确') {
          this.handleShowTextToast('暂不支持此快递');
        } else {
          this.handleShowTextToast(json.msg);
        }
      }
    },

    writeRefundInfoNoJump: async function(otherRefundId) {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
      const json = await api.buyerReturn({
        method: 'POST',
        header: {
          jwt: customerInfo.jwt
        },
        query: {
          expressCode: this.expressCode,
          refundId: otherRefundId,
          trackingNumber: this.expressNumber
        }
      });
      if (json.code === 1000) {
        let timestamp = new Date().getTime();
          that.$sr.track('custom_order', {
        				 order: {
        				   order_id: that.orderCode.toString(),
        				   order_time: new Date(that.orderTimeStamp.replace(/-/g,"/")).getTime() || new Date(that.orderTimeStamp).getTime(),
        				   order_status: 'refund',
        				   refund_time: timestamp
        				 },
        				 sub_orders: [
        				   {
        					 sub_order_id: that.orderCode.toString(),
        					 order_amt: parseFloat(that.fullOrderInfo.itemTotal),
        					 pay_amt: parseFloat(that.fullOrderInfo.payment)
        				   }
        				 ]
        				 // more...
          });
      } else {
        if (json.msg == 'expressCode不正确') {
          this.handleShowTextToast('暂不支持此快递');
        } else {
          this.handleShowTextToast(json.msg);
        }
      }
    },

    toRmaReturn: async function(e) {
      let that = this;
      var reg = /^[0-9a-zA-Z]{9,}$/;
      if (reg.test(this.expressNumber) == true && this.expressName !== '') {
        that.writeRefundInfo();
        if (that.refundIdArr.length > 0) {
          for (let i in that.refundIdArr) {
            that.writeRefundInfoNoJump(that.refundIdArr[i]);
          }
        }
      } else {
        this.handleShowTextToast('物流单不正确');
      }
      return false;
    }
  }
};
</script>
<style lang="less">
@import '@/static/styles/style';
.rma_success {
  margin-top: 100rpx;
  padding: 0 20rpx;
}

.rma_success h4 {
  text-align: center;
  margin-bottom: 30rpx;
  margin-top: 20rpx;
}

.orderNumber,
.ramAddress {
  text-align: center;
  margin: 80rpx 0;
}

.ramAddress {
  text-align: left;
}

.ramAddress p {
  margin-top: 20rpx;
  display: block;
  color: #999;
}

.ramAddress strong {
  font-weight: 700;
}

.bottom-section {
  width: 100%;
  position: relative;
  margin-top: 40rpx;
}

.bottom-section .a-button {
  margin: 0rpx 0 46rpx 0;
}

.bottom-section .a-link {
  position: absolute;
  top: 25px;
  left: 44%;
}

.a-input {
  border: none;
  background-color: #e7e7e7;
  color: #444;
  height: 30px;
  padding: 0 0 0 8rpx;
}

.o-page-content.cofs-page {
  border-top: 1px solid #efefef;
}

.expForm {
  margin-top: 25px;
}

.expForm label {
  margin: 40rpx 0 4rpx;
  display: block;
}

.rma_express {
  padding: 30rpx;
  background-color: #fff;
}

.rma_express h4 {
  border-bottom: 2px solid #f6f6f6;
  padding: 0 0 30px;
  text-align: center;
  margin: 0 0 0 10px;
  display: block;
  font-size: 36rpx;
}

.rmaRet {
  text-align: center;
}

.rmaRet .a-link {
  position: static;
}

.listMob {
  margin-bottom: 20rpx;
}

picker {
  position: relative;
}

.picker {
  height: 26px;
  line-height: 26px;
  border: 1px solid #ccc;
  padding-left: 10rpx;
}

.rma_listMob h4 {
  font-size: 18px;
  text-align: center;
  margin: 20px 0;
  display: block;
}

.gInfo {
  overflow: hidden;
  padding: 30rpx 35rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.gInfo p {
  margin-bottom: 8px;
  display: block;
}

.gInfo strong {
  margin: 5px 0 20px;
  font-weight: 400;
  display: block;
}

.ram_listImg {
  display: block;
  margin-right: 20px;
  width: 30%;
  float: left;
}

.a-icon-arrow-down-small {
  top: 10rpx;
}

.rma_order_details {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx 35rpx;
}

.rma_order_details p {
  display: block;
  margin-bottom: 10rpx;
}

.rma_order_details p:last-child {
  margin: 0;
}

page {
  background-color: #f9f9f9;
}

.rma_success {
  padding: 170rpx 20rpx 0;
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 2;
}

.rma_success h4 {
  text-align: center;
  margin-bottom: 15px;
  font-size: 36rpx;
  display: block;
}

.rma_success strong {
  font-weight: 700;
}

.rma_success p {
  display: block;
  text-align: center;
}

.rma_success .btn {
  width: 80%;
  height: 60rpx;
  line-height: 60rpx;
  position: relative;
  display: block;
  margin: 120rpx auto 46rpx;
}

.rma_success .a-link {
  text-decoration: underline;
  margin-top: 8rpx;
}

.rma_success .icon-ok {
  font-size: 42rpx;
  margin-right: 10rpx;
}

.copy-btn {
  margin-left: 70rpx;
  color: #ff571a;
}

// 退货商品
.refundItems {
  padding-top: 80rpx;
}
.pageTitle {
  margin-left: 20rpx;
}
.good_list {
  display: flex;
  overflow: hidden;
  position: relative;
  margin: 20rpx 20rpx 0;
  padding-bottom: 24rpx;
  border-bottom: 1px solid #efefef;
}

.image_box {
  margin-right: 40rpx;
  float: left;
  min-height: 180rpx;
  image {
    width: 120rpx;
    // height: 180rpx;
    display: block;
  }
}

.product_name {
  color: #414141;
  font-size: 32rpx;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

.product_rule {
  font-size: 26rpx;
  color: #757575;
  padding-top: 16rpx;
  display: none;
}

.price {
  color: #de0000;
  font-size: 34rpx;
  font-weight: 600;
}

.goods {
  padding: 0;
  float: right;

  .order_footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 20rpx;
  }

  .order_state {
    color: #ff4856;
    font-size: 32rpx;
  }

  .btn_group {
    display: flex;
    align-items: right;

    .btn {
      font-size: 25rpx;
      padding: 10rpx 10rpx;
      text-align: center;
      margin: 0 auto;
      width: 100%;
    }

    .btn_del {
      color: #333;
      border: 1px solid #ccc;
    }
  }
}

.product_info {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
}

.cost_price {
  padding-left: 20rpx;
}

.textInfo strong {
  font-size: 26rpx;
  margin: 2px 0 5px;
  font-weight: normal;
  display: block;
  height: 40rpx;
  line-height: 40rpx;
  overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    max-width: 400rpx;
}

.textInfo p {
  height: 40rpx;
  line-height: 40rpx;
  display: block;
  font-size: 26rpx;
}

.product_info {
  display: block;
  position: absolute;
  top: 6rpx;
  right: 20rpx;
}

.product_info .price,
.product_info .goods_num {
  text-align: right;
  font-size: 28rpx;
  font-weight: normal;
  color: #444;
}

.product_info .goods_num {
  color: #bbb;
}

.os_text {
  font-size: 12px;
}

.rma_state span {
  float: right;
  text-decoration: underline;
}

.label-1__icon {
  position: relative;
  top: 58rpx;
  width: 30rpx;
  height: 30rpx;
  background: #fcfff4;
  border: 1px solid #cccccc;
  margin-right: 20rpx;
}

.icon_check {
  position: absolute;
}
</style>
